package cn.wind.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.wind.po.ActiveUser;
import cn.wind.po.SysPermission;
import cn.wind.po.SysUser;
import cn.wind.service.LoginService;

/**
 * 
 * <p>
 * Title: CustomRealm
 * </p>
 * <p>
 * Description:自定义realm
 * </p>
 * @version 1.0
 */
public class CustomRealm extends AuthorizingRealm {
	
	private static Logger log = Logger.getLogger(CustomRealm.class);
	@Autowired
	private LoginService loginService;
	// 设置realm的名称
	@Override
	public void setName(String name) {
		super.setName("customRealm");
	}

	// 用于认证
	//没有连接数据库的方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// token是用户输入的用户名和密码 
		// 第一步从token中取出用户名
		String userCode = (String) token.getPrincipal();
		// 第二步：根据用户输入的userCode从数据库查询
		// 如果查询不到返回null
		SysUser userByUserName = loginService.getUserByUserName(userCode);
		if(userByUserName==null){//
			return null;
		}
		// 模拟从数据库查询到密码
		String password = userByUserName.getPassword();
		// 如果查询到返回认证信息AuthenticationInfo
		//activeUser就是用户身份信息
		ActiveUser activeUser = new ActiveUser();
		activeUser.setUserid(userByUserName.getId());
		activeUser.setUsercode(userByUserName.getUsercode());
		activeUser.setUsername(userByUserName.getUsername());
		//根据用户id取出菜单
		//通过service取出菜单 
		List<SysPermission> menus  = loginService.getMenusByUserId(userByUserName.getId());
		//将用户菜单 设置到activeUser
		activeUser.setMenus(menus);
		//将activeUser设置simpleAuthenticationInfo
		//没有设置md5加密
		/*SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, password, this.getName());
		*/
		String salt = userByUserName.getSalt();
		//md5加密
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, password,ByteSource.Util.bytes(salt), this.getName());
		
		return simpleAuthenticationInfo;
	}
	

	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		//从 principals获取主身份信息
		//将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型），
		ActiveUser activeUser =  (ActiveUser) principals.getPrimaryPrincipal();
		String userid = activeUser.getUserid();
		//根据身份信息获取权限信息
		//从数据库获取到权限数据
		List<String> permissions = loginService.permissions(userid);
		//查到权限数据，返回授权信息(要包括 上边的permissions)
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//将上边查询到授权信息填充到simpleAuthorizationInfo对象中
		simpleAuthorizationInfo.addStringPermissions(permissions);
		return simpleAuthorizationInfo;
	}
	
	//清除缓存
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}
}
